<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Session;

class Login extends Controller
{
    public function login_deng(){
		$user = Session::get('id');
		$id = $_GET['id']?$_GET['id']:0;
		$uid = $_GET['uid']?$_GET['uid']:0;
		$gz_uid = $_GET['gz_uid']?$_GET['gz_uid']:0;
		
		$add_uid = $_GET['add_uid']?$_GET['add_uid']:0;

		$type = $_GET['apply'];

		if($user){
			echo "<script>window.location.href='/index/index/index'</script>";
		}
		$this->view->assign('id',$id);
		$this->view->assign('uid',$uid);
		$this->view->assign('gz_uid',$gz_uid);
		$this->view->assign('add_uid',$add_uid);
		$this->view->assign('type',$type);

		return $this->view->fetch();
    }

    public function login(){
		$tel = $_POST['tel'];
		$pwd = md5($_POST['pwd']);
        if($tel){
            $user = Db::table("tp_user")->where(array("tel"=>$tel))->count();
            if($user){
                $res = Db::table("tp_user")->where(array("tel"=>$tel,"pwd"=>$pwd))->find();

                //用户登录成功
                if($res){
                    if($res['img'] == '' || $res['name'] == '' || $res['age'] == 0 || $res['sex'] == -1){
                        $info = [
                            'code' => -3,
                            'data' => $res['id']
                        ];
                        return json_encode($info);
                    }else{
                        if($res){
                            //  			Session::set('name',$res['id']);
                            $url = Session::get('url')?Session::get('url'):'/index/index/index';
                            if($url){
                                Session::set('id',$res['id']);
                                $info = [
                                    'code' => 1,
                                    'data' => $url,
                                    'user_id' => Session::get('id')
                                ];
                                return json_encode($info);
                            }
                        }
                    }
                }else{
                    $info = [
                        'code' => -1
                    ];
                    return json_encode($info);
                }
            }else{
                $info = [
                    'code' => -2
                ];
                return json_encode($info);
            }
        }
    }
	/*
	 *个人信息的跳转链接中加上id 
	 */
	public function url_add_id(){
		$id = Session::get('id');
		echo $id;
	}

    public function login_zhu(){
    	return $this->view->fetch();
    }
    public function register(){
    	$tel = $_POST['tel'];
    	$send_code = Session::get("send_code");
    	$code = $_POST['code'];
    	$pwd = $_POST['pwd']?md5($_POST['pwd']):$_POST['pwd'];
    	$sex = $_POST['sex'];
    	$data['tel'] = $tel;
    	$data['pwd'] = $pwd;
    	$data['sex'] = $sex;
    	$data['Credit'] = 100;
    	
    	if($send_code == $code && $code != null){
    		//验证码正确
            $result = preg_match_all("/^[\w-\.]{6,16}$/", $_POST['pwd'], $matches);
            $pwd_len = strlen($_POST['pwd']);
            if($pwd_len < 6 || $pwd_len > 16){
                echo -4;//密码长度为6-16位
            }else{
                if($result == 1){
                    //查询账号是否已经被注册
                    $is_register = Db::table('tp_user')->where(array('tel'=>$tel))->count();

                    if($is_register == 0){
                        $res = Db::table('tp_user')->insert($data);
                        if($res){
                            echo "1";//注册成功
                        }
                    }else{
                        echo "-1";//该手机号码已被注册！
                    }
                }else{
                    echo "-2";//密码由数字,字母,'_','-'组成
                }
            }
    	}else{
    		echo "-3";//验证码错误
    	}
    }
    public function term(){
    	return $this->view->fetch();
    }
    	/*
 * /获取用户微信openid
 */
	public function getopenid(){
		$code = $_GET['code'];
		//var_dump($code);exit;
		header ( "Content-type: text/html; charset=utf-8" );
		vendor ( 'ThirdLogin.WxLogin' );
		$appId = WXAPPID;
		$appKey = WXAPPKEY;
		$wx = new \WxLogin($appId,$appKey,$code);
		//得到access_token验证值
		$accessToken = $wx->getToken();
		if(!$accessToken){
			$this->success('登录失败', '/index/login/login_deng');
		}
		//得到用户的openid(登陆用户的识别码)和Client_id
		$openId = $wx->getOpenId();
		if($openId!=""){
			$arr['openid'] = $openId;
			$user = Db::table("tp_user")->where($arr)->find();
			//判断是否注册
			if($user){
				Session::set('id',$user['id']);
				Session::set('openId',$openId);
				$this->success('登录成功', "/index/index/index");
			}else{
				$user_info = $wx->getUserInfo($openId,$accessToken);
				$info['name'] = $user_info['nickname'];
				$info['openid'] = $user_info['openid'];
				$info['img'] = $user_info['headimgurl'];
				$info['sex'] = $user_info['sex'];
				$inse = Db::table("tp_user")->insert($info);
				if($inse){
					$user = Db::table("tp_user")->where($arr)->find();
					Session::set('id',$user['id']);
					$this->success('登录成功', '/index/index/index');
				}
			}
		}
	}
	/**
	 * QQ登录回调方法
	 */
	public function qqLoginCallback(){
			header ( "Content-type: textml; charset=utf-8" );
			vendor ( 'ThirdLogin.QqLogin' );

			$appId = QQAPPID;
		//var_dump($_REQUEST);exit;
			$appKey = QQAPPKEY;
			//回调接口，接受QQ服务器返回的信息的脚本
			$callbackUrl = "http://tour.mgtvshop.com/index/login/qqLoginCallback";
			//实例化qq登陆类，传入上面三个参数
			$qq = new \QqLogin($appId,$appKey,$callbackUrl);

			//得到access_token验证值
			$accessToken = $qq->getToken();

			if(!$accessToken){
				$this->success('登录失败', '/index/login/login_deng');
			}
			//得到用户的openid(登陆用户的识别码)和Client_id
			$arr = $qq->getClientId($accessToken);
			if(isset($arr['openid'])){
				$clientId = $arr['client_id'];
				$openId = $arr['openid'];
				$arr1['openId'] = $arr['openid'];
				$um = Db::table('tp_user')->where($arr1)->find();
				//已注册，则直接登录
				if($um){
					//var_dump($um);exit;
					Session::set('id',$um['id']);
					$this->success('登录成功', '/index/index/index');
				}else{
					//未注册，则先注册
					$arr = $qq->getUserInfo($clientId,$openId,$accessToken);
//var_dump($arr);exit;
					$obj["name"] = $arr["nickname"];
					if($arr["gender"] == "男"){
						$obj["sex"] = 1;
					}else{
						$obj["sex"] = 0;
					}
					$obj["openid"] = $arr1['openId'];
					$obj["user_type"] = 2;
					$obj["img"] = $arr["figureurl_qq_2"];
					$um = Db::table("tp_user")->insert($obj);
					if($um){
						$user = Db::table("tp_user")->where($arr1)->find();
						Session::set('id',$user['id']);
						$this->success('登录成功', '/index/index/index');
					}
				}
			}else{
				$this->redirect("Public/login");
			}
	}
	/*
	 *微博登录
	 */
	public function  logings(){
		vendor( 'weibo.config' );
		vendor( 'weibo.saetv2#ex#class' );
		$o = new \SaeTOAuthV2(WB_AKEY ,WB_SKEY );
		$code_url = $o->getAuthorizeURL( WB_CALLBACK_URL );
		//var_dump($code_url);exit;
		header("location:".$code_url);
	}
    public function wblogin(){
		vendor( 'weibo.config' );
		vendor( 'weibo.saetv2#ex#class' );
		$o = new \SaeTOAuthV2(WB_AKEY ,WB_SKEY );
		 //file_put_contents('ios.txt',$_REQUEST['code']);
         if (isset($_REQUEST['code'])) {
	         $keys = array();
	         $keys['code'] = $_REQUEST['code'];
	         $keys['redirect_uri'] = WB_CALLBACK_URL;
			 $token = $o->getAccessToken( 'code', $keys );
			 if ($token) {
				 $dd['openid'] = $token['access_token'];

				 $res = Db::table('tp_user')->where($dd)->find();

				 if($res){
					 Session::set('id',$res['id']);
					 $this->success('登录成功', '/index/index/index');
				 }else{
					 $c = new \SaeTClientV2( WB_AKEY , WB_SKEY ,$token["access_token"]);
					 $ms = $c->home_timeline(); // done
					 $uid_get = $c->get_uid();
					 $uid =  $token['uid'];
					 $user_message = $c->show_user_by_id( $token['uid']);//根据ID获取用户等基本信息
					 //var_dump($user_message);exit;
					 $data['name'] = $user_message['screen_name'];
					 $data['img'] = $user_message['profile_image_url'];
					 $data['openid'] = $token['access_token'];
					 $data["user_type"] = 3;
					 $user = Db::table('tp_user')->insert($data);
					 if($user){
						 $ios = Db::table('tp_user')->where($data)->find();
						 Session::set('id',$ios['id']);
						 $this->success('登录成功', '/index/index/index');
					 }
				 }
			 } else {
				 echo "授权失败";exit;
			 }
         }else{
			 echo "获取code值失败";exit;
		 }
    }
    public function edit_pwd(){
        return $this->view->fetch();
    }
    public function update_pwd(){
        $data = input('param.');
        $new_pwd_len = strlen($data['new_pwd']);
        $count = Db::table('tp_user')->where('tel',$data['tel'])->count();//查找是否存在该账号
        if($count > 0){
            $is_true = Db::table('tp_user')->where(array('tel' => $data['tel'], 'pwd' => md5($data['old_pwd'])))->count();
            if($is_true > 0){
                if($new_pwd_len < 6 || $new_pwd_len > 16) {
                    return json(['code' => -3, 'msg' => '新密码长度为6-16位']);
                }else{
                    if($data['old_pwd'] == $data['new_pwd']){
                        return json(['code' => -4, 'msg' => '新旧密码不能一致']);
                    }else{
                        $res = Db::table('tp_user')->where('tel',$data['tel'])->setField('pwd',md5($data['new_pwd']));
                        if($res){
                            return json(['code' => 200, 'msg' => '修改密码成功！']);
                        }else{
                            return json(['code' => -5, 'msg' => '修改密码失败！']);
                        }
                    }
                }
            }else{
                return json(['code' => -2, 'msg' => '旧密码不正确']);
            }
        }else{
            return json(['code' => -1, 'msg' => '该账号不存在']);
        }

        return json(['msg' => $data]);
    }
    /*
     * 找回密码
     * */
    public function forget_pwd(){
        return $this->view->fetch();
    }
    public function is_have(){
        $data = input('param.');
        $count = Db::table('tp_user')->where('tel',$data['tel'])->count();
        if($count == 0){
            return json(['code' => -1,'msg' => '该号码不存在，请重新输入！' ]);
        }else{
            return json(['code' => 200]);
        }
    }
    /*
     * 修改旧密码
     * */
    public function find_pwd(){
        $code = session::get('forget_code');
        $data = input('param.');

        if($code == $data['yzm']){
            $res = Db::table('tp_user')->where('tel',$data['tel'])->setField('pwd',md5($data['new_pwd']));
            if($res){
                return json(['code' => 200, 'msg' => '修改密码成功！']);
            }else{
                return json(['code' => -2, 'msg' => '新密码不能和旧密码一致！']);
            }
        }else{
            return json(['code' => -1, 'msg' => '短信验证码填写错误']);
        }
    }
}
